package types

import (
	"crypto/md5"
	"encoding/hex"
	"fmt"
	"github.com/flaravel/quanlaolao/pkg/config"
	"github.com/flaravel/quanlaolao/pkg/logger"
	"github.com/speps/go-hashids"
	"math/rand"
	"strconv"
)

// Int64ToString 将 int64 转换为 string
func Int64ToString(num int64) string {
	return strconv.FormatInt(num, 10)
}

// Uint64ToString 将 uint64 转换为 string
func Uint64ToString(num uint64) string {
	return strconv.FormatUint(num, 10)
}

// StringToInt 将字符串转换为 int
func StringToInt(str string) int {
	if str == "" {
		return 0
	}
	i, err := strconv.Atoi(str)
	if err != nil {
		logger.LogError(err)
	}
	return i
}

// Uint2String 将字符串转换为 int
func Uint2String(str string) int {
	i, err := strconv.Atoi(str)
	if err != nil {
		logger.LogError(err)
	}
	return i
}

// 随机字符串
func RandToken(len int) string {
	b := make([]byte, len)
	rand.Read(b)
	return fmt.Sprintf("%x", b)
}

func EncodeMD5(value string) string {
	m := md5.New()
	m.Write([]byte(value))

	return hex.EncodeToString(m.Sum(nil))
}

//Encode 混淆
func IdEncode(data int) string {
	hd := hashids.NewData()
	hd.Salt = config.GetString("app.key")
	h, _ := hashids.NewWithData(hd)
	e, _ := h.Encode([]int{data})
	return e
}

//Decode 还原混淆
func IdDecode(data string) (int,error) {
	hd := hashids.NewData()
	hd.Salt = config.GetString("app.key")
	h, _ := hashids.NewWithData(hd)
	e, err := h.DecodeWithError(data)
	if err != nil {
		return 0,err
	}
	return e[0], nil
}